package com.imooc.mq;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * fanout发布订阅工作模式消费者B (不用交换机)
 * @author liansen
 * @create 02-16-15:51
 */
public class PublishConsumerDemoB {

    public static void main(String[] args) throws Exception {

        //创建工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.31.68");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");

        //创建连接
        Connection connection = factory.newConnection();
        //创建信道
        Channel channel = connection.createChannel();

        channel.queueDeclare("fanout_queue_b", true, false, false, null);

        /**
         * 回调函数-处理监听到的消息
         * String consumerTag, 消息的标签标识
         * Envelope envelope, 一些信息,比如交换机，路由等信息
         * properties, 配置信息
         * byte[] body 收到的消息数据
         */
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                System.out.println("body:" + new String(body));
            }
        };

        /**
         * String queue, 监听的队列名称
         * boolean autoAck, 是否自动确认，true:告知mq消费者已经消费了这个消息
         * Consumer callback 回调函数, 处理监听到的消息
         */
        channel.basicConsume("fanout_queue_b", true, consumer);

    }
}
